import { BaseService, CoolCommException } from "@cool-midway/core";
import { Inject, Provide } from "@midwayjs/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Equal, In, Repository, EntityManager } from "typeorm";
import { Context } from "@midwayjs/koa";
import { ProviderInfoEntity, ProviderStatus } from "../entity/info";
import { AddProviderDTO, UpdatePartnerRelationDTO, UpdateProviderMemberDTO } from "../dto/provider";
import { ProviderProfileEntity } from "../entity/profile";
import { CapacityEntity } from "../../transport/entity/capacity";
import { ProviderTeamEntity } from "../entity/team";
import { TransportType } from "../../transport/entity/type";
import { TenantInfoEntity } from "../../tenant/entity/info";
import { ProviderPartnerEntity } from "../entity/partner";

export type ProviderMember = Omit<ProviderProfileEntity, 'hasId' | 'save' | 'remove' | 'softRemove' | 'recover' | 'reload'> & {
    providerInfo: ProviderInfoEntity;
    relationType: 'owner' | 'partner';
    status: ProviderStatus;
    owner: boolean;
    partnerStatus?: any;
}

@Provide()
export class ProviderProviderService extends BaseService {

    // 服务人员登录信息实体模型
    @InjectEntityModel(ProviderInfoEntity)
    providerInfoEntity: Repository<ProviderInfoEntity>

    // 服务人员信息实体模型
    @InjectEntityModel(ProviderProfileEntity)
    providerProfileEntity: Repository<ProviderProfileEntity>

    // 运力实体模型
    @InjectEntityModel(CapacityEntity)
    capacityEntity: Repository<CapacityEntity>

    // 团队实体模型
    @InjectEntityModel(ProviderTeamEntity)
    providerTeamEntity: Repository<ProviderTeamEntity>

    // 租户信息实体模型
    @InjectEntityModel(TenantInfoEntity)
    tenantInfoEntity: Repository<TenantInfoEntity>

    // 合作关系实体模型
    @InjectEntityModel(ProviderPartnerEntity)
    providerPartnerEntity: Repository<ProviderPartnerEntity>

    @Inject()
    ctx: Context





    async add(dto: AddProviderDTO) {
        const currentProviderId = this.ctx.provider.id;
        return await this.providerInfoEntity.manager.transaction(async (manager) => {
            // 操作0: 获取当前操作人员拥有的团队
            const currentProviderTeam = await manager.findOne(ProviderTeamEntity, {
                where: { ownerProviderId: Equal(currentProviderId) },
            })
            if (!currentProviderTeam) {
                throw new CoolCommException('您还未创建团队')
            }

            // 查询登录信息是否存在
            let loginInfo = await manager.findOne(ProviderInfoEntity, {
                where: { phone: dto.phone },
            })
            if (!loginInfo) {
                // 不存在的话，创建登录信息
                loginInfo = await manager.save(ProviderInfoEntity, {
                    phone: dto.phone,
                    ip: this.ctx.ip,
                    status: ProviderStatus.NORMAL,
                })
                // 创建基础信息并绑定团队
                await this.createProfileWithCapacity(manager, loginInfo.id, dto, currentProviderTeam.id)
                return true;
            }

            // 存在的话，判断是否存在基本信息
            const providerProfile = await manager.findOne(ProviderProfileEntity, {
                where: { providerId: loginInfo.id },
            })
            if (providerProfile) {
                // 已有基本信息，判断是否已关联团队（虚拟列由运力的 teamId 推导）
                if (providerProfile.teamId) {
                    throw new CoolCommException('该服务人员已关联团队')
                }
                // 未关联团队则直接更新运力的团队
                const updateResult = await manager.update(CapacityEntity, { id: providerProfile.capacityId }, { teamId: currentProviderTeam.id })
                if (!updateResult.affected) {
                    throw new CoolCommException('运力信息不存在')
                }
                return true;
            }

            // 不存在基本信息，则创建并绑定团队
            await this.createProfileWithCapacity(manager, loginInfo.id, dto, currentProviderTeam.id)
            return true;
        })
    }

    /**
     * 创建运力与个人档案并绑定团队
     */
    private async createProfileWithCapacity(manager: EntityManager, providerId: number, dto: AddProviderDTO, teamId: number) {
        const capacity = await manager.save(CapacityEntity, {
            type: TransportType.PROVIDER,
            teamId: teamId
        })

        await manager.save(ProviderProfileEntity, {
            providerId: providerId,
            capacityId: capacity.id,
            name: dto.name,
            gender: dto.gender,
            photo: dto.photo,
            residence: dto.residence,
        })
    }



    // 更改所属关系为合作关系
    async changeOwnerToPartner(providerId: number) {
        const currentProviderId = this.ctx.provider.id;
        return await this.providerPartnerEntity.manager.transaction(async (manager) => {
            const currentProviderTeam = await manager.findOne(ProviderTeamEntity, {
                where: { ownerProviderId: Equal(currentProviderId) }
            })
            if (!currentProviderTeam) {
                throw new CoolCommException('您未创建团队，无法更改所属关系为合作关系')
            }

            // 查询目标服务人员基础信息（包含 capacityId 用于解绑所属）
            const targetProviderProfile = await manager.findOne(ProviderProfileEntity, {
                where: { providerId: Equal(providerId) }
            })
            if (!targetProviderProfile) {
                throw new CoolCommException('目标服务人员基础信息不存在')
            }

            // 如当前属于本团队，则取消所属关系：将对应运力的 teamId 置空
            if (targetProviderProfile.teamId == currentProviderTeam.id) {
                const res = await manager.update(CapacityEntity, { id: targetProviderProfile.capacityId }, { teamId: null })
                if (!res.affected) {
                    throw new CoolCommException('运力信息不存在，无法取消所属关系')
                }
            }

            // 防重：检查是否已存在合作关系
            const partner = await manager.findOne(ProviderPartnerEntity, {
                where: {
                    providerId: Equal(targetProviderProfile.providerId),
                    teamId: Equal(currentProviderTeam.id)
                }
            })
            if (partner) {
                throw new CoolCommException('该服务人员已存在合作关系')
            }

            return await manager.save(ProviderPartnerEntity, {
                providerId,
                teamId: currentProviderTeam.id,
            });
        })
    }

    // 更改合作关系为所属关系
    async changePartnerToOwner(targetProviderId: number) {
        const currentProviderId = this.ctx.provider.id;

        // 第一步，查询目标服务人员基础信息
        const targetProviderProfile = await this.providerProfileEntity.findOne({
            where: { providerId: Equal(targetProviderId) }
        })
        if (!targetProviderProfile) {
            throw new CoolCommException('目标服务人员基础信息不存在')
        }

        // 第二步，查询目标服务人员合作关系
        const targetProviderPartner = await this.providerPartnerEntity.findOne({
            where: { providerId: Equal(targetProviderId), teamId: Equal(currentProviderId) }
        })
        if (!targetProviderPartner) {
            throw new CoolCommException('目标服务人员不存在合作关系')
        }

        // 第三步，取消合作关系
        await this.providerPartnerEntity.delete(targetProviderPartner.id)

        // 第四步，更新目标服务人员所属关系
        await this.providerTeamEntity.update(targetProviderPartner.teamId, { ownerProviderId: targetProviderProfile.providerId })
    }

    // 删除合作关系与所属关系
    async deleteProviderRelation(targetProviderId: number) {
        if (!this.ctx.team) {
            throw new CoolCommException('无权限~')
        }
        return await this.providerPartnerEntity.manager.transaction(async (manager) => {
            // 第一步，查询目标服务人员合作关系
            const targetProviderPartner = await manager.findOne(ProviderPartnerEntity, {
                where: { providerId: Equal(targetProviderId), teamId: Equal(this.ctx.team?.id) }
            })
            if (targetProviderPartner) {
                await manager.delete(ProviderPartnerEntity, targetProviderPartner.id)
            }

            // 第二步，查询目标服务人员所属关系
            //    1. 查询目标人员对应的运力ID
            const targetProviderProfile = await manager.findOne(ProviderProfileEntity, {
                where: { providerId: Equal(targetProviderId) }
            })
            if (!targetProviderProfile) {
                throw new CoolCommException('目标服务人员不存在')
            }
            //    2. 取消运力与团队的关联
            await manager.update(CapacityEntity, { id: targetProviderProfile.capacityId }, { teamId: null })
        })
    }





    /**
     * 根据当前团队ID获取该团队下所有的合作成员及所属成员
     */
    async getTeamMembers(teamId: number) {
        if (!teamId) {
            throw new CoolCommException('团队信息不存在')
        }

        const team = await this.providerTeamEntity.findOne({
            where: { id: Equal(teamId) }
        });
        if (!team) {
            throw new CoolCommException('团队信息不存在')
        }

        // 查询合作成员：从 ProviderPartnerEntity 中查询该团队的合作成员
        const partners = await this.providerPartnerEntity.find({
            where: { teamId: Equal(teamId) }
        });

        // 查询所属成员：从 CapacityEntity 中查询该团队的所属成员
        const capacities = await this.capacityEntity.find({
            where: { teamId: Equal(teamId), type: TransportType.PROVIDER }
        });

        // 获取合作成员的详细信息
        const partnerProviderIds = partners.map(p => p.providerId);
        const partnerProfiles = partnerProviderIds.length > 0
            ? await this.providerProfileEntity.find({
                where: { providerId: In(partnerProviderIds) }
            })
            : [];

        const teamOwnerProviderInfo = await this.providerInfoEntity.findOne({
            where: { id: Equal(team.ownerProviderId) }
        })
        if (!teamOwnerProviderInfo) {
            throw new CoolCommException('团队负责人信息不存在')
        }

        const teamOwnerProfile = await this.providerProfileEntity.findOne({
            where: { providerId: Equal(teamOwnerProviderInfo.id) }
        })
        if (!teamOwnerProfile) {
            throw new CoolCommException('团队负责人信息不存在')
        }




        // 获取所属成员的详细信息
        const ownerCapacityIds = capacities.map(c => c.id);
        const ownerProfiles = ownerCapacityIds.length > 0
            ? await this.providerProfileEntity.find({
                where: { capacityId: In(ownerCapacityIds) }
            })
            : [];


        // 获取所有服务人员的登录信息
        const allProviderIds = [
            teamOwnerProviderInfo?.id,
            ...partnerProviderIds,
            ...ownerProfiles.map(p => p.providerId)
        ];
        const uniqueProviderIds = [...new Set(allProviderIds.filter((id): id is number => typeof id === 'number'))];
        const providerInfos = uniqueProviderIds.length > 0
            ? await this.providerInfoEntity.find({
                where: { id: In(uniqueProviderIds) }
            })
            : [];
        // const owner = teamOwnerProviderInfo?.id === this.ctx.provider.id;

        // 组装合作成员数据
        const partnerMembers = partnerProfiles.map(profile => {
            const partner = partners.find(p => p.providerId === profile.providerId);
            const info = providerInfos.find(i => i.id === profile.providerId);
            return {
                ...profile,
                providerInfo: info!,
                relationType: 'partner' as const,
                status: info!.status,
                partnerStatus: partner?.status,
                owner: false,
                // owner: owner
            };
        }) as ProviderMember[];

        // 组装所属成员数据
        const ownerMembers = ownerProfiles.map(profile => {
            const info = providerInfos.find(i => i.id === profile.providerId);
            return {
                ...profile,
                providerInfo: info!,
                relationType: 'owner' as const,
                status: info!.status,
                owner: false,
                // owner: owner
            };
        }) as ProviderMember[];


        // 合并所有成员到一个数组中
        const allMembers: ProviderMember[] =
            [
                {
                    ...teamOwnerProfile,
                    providerInfo: teamOwnerProviderInfo!,
                    relationType: 'owner' as const,
                    status: teamOwnerProviderInfo!.status,
                    owner: true
                },
                ...partnerMembers,
                ...ownerMembers
            ];

        return {
            list: allMembers,
            total: allMembers.length,
            partners: partnerMembers.length,
            owners: ownerMembers.length,
        };
    }

    /**
     * 查询团队成员详情
     */
    async getTeamMemberDetail(providerId: number, teamId?: number) {
        const currentTeamId = teamId ?? this.ctx.team?.id;
        if (!currentTeamId) {
            throw new CoolCommException('团队信息不存在')
        }
        if (!providerId) {
            throw new CoolCommException('服务人员信息不存在')
        }

        const { list } = await this.getTeamMembers(currentTeamId);
        const member = list.find(item => item.providerId === providerId);
        if (!member) {
            throw new CoolCommException('该服务人员不在当前团队')
        }

        return member;
    }

    /**
     * 编辑团队成员档案信息
     */
    async updateMemberProfile(dto: UpdateProviderMemberDTO) {
        const teamId = this.ctx.team?.id;
        if (!teamId) {
            throw new CoolCommException('团队信息不存在')
        }
        if (!dto?.providerId) {
            throw new CoolCommException('服务人员信息不存在')
        }

        // 先确保目标成员隶属于当前团队
        await this.getTeamMemberDetail(dto.providerId, teamId);

        const profile = await this.providerProfileEntity.findOne({
            where: { providerId: Equal(dto.providerId) }
        })
        if (!profile) {
            throw new CoolCommException('服务人员档案不存在')
        }

        const editableFields: (keyof UpdateProviderMemberDTO)[] = [
            'name',
            'gender',
            'age',
            'photo',
            'residence',
            'experienceYears',
            'drivingYears',
            'serviceCount',
            'comprehensiveScore',
            'introduction',
            'serviceScope',
            'style',
            'displayModule',
            'serviceContent'
        ];

        const payload: Partial<ProviderProfileEntity> = {};
        for (const field of editableFields) {
            const value = dto[field];
            if (value !== undefined) {
                (payload as any)[field] = value;
            }
        }

        if (!Object.keys(payload).length) {
            return this.getTeamMemberDetail(dto.providerId, teamId);
        }

        await this.providerProfileEntity.update({ providerId: dto.providerId }, payload);
        return this.getTeamMemberDetail(dto.providerId, teamId);
    }

    /**
     * 编辑合作关系
     */
    async updatePartnerRelation(dto: UpdatePartnerRelationDTO) {
        const teamId = this.ctx.team?.id;
        if (!teamId) {
            throw new CoolCommException('团队信息不存在')
        }
        if (!dto?.providerId) {
            throw new CoolCommException('服务人员信息不存在')
        }

        const partner = await this.providerPartnerEntity.findOne({
            where: {
                providerId: Equal(dto.providerId),
                teamId: Equal(teamId)
            }
        })
        if (!partner) {
            throw new CoolCommException('合作关系不存在')
        }

        await this.providerPartnerEntity.update(partner.id, {
            status: dto.status
        })

        return this.getTeamMemberDetail(dto.providerId, teamId);
    }

}